package com.qunar.crawler.utils;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import sun.tools.tree.ThisExpression;

/**
 * 模拟人浏览行为(晚上停止...) 在行为过滤中<br>
 * p1的概率确认是不是在规定的时间区内抓取,不是则暂停m分钟<br>
 * p2的概率暂停n分钟<br>
 * 
 * @author waynechen Jun 4, 2012 5:38:53 PM
 */
public class HumanActionSimulator4VisitingWeb {
    private static List<Point2D<String>> intervals = new ArrayList<Point2D<String>>();
    private static double p1;
    private static double p2;
    private static HumanActionSimulator4VisitingWeb ha = null;

    static {
        List<String> list = ConfigBatchInit.getStringList("HumanAction4VisitingWeb");
        for (String line : list) {
            line = line.replace(" ", "");
            if (line.startsWith("p1=")) {
                p1 = Double.parseDouble(line.split("=")[1]);
            } else if (line.startsWith("p2=")) {
                p2 = Double.parseDouble(line.split("=")[1]);
            } else {
                String[] split = line.split("~");
                intervals.add(new Point2D<String>(split[0], split[1]));
                
            }
        }
    }

    public static synchronized HumanActionSimulator4VisitingWeb getInstance() {

        if (ha == null) {
            ha = new HumanActionSimulator4VisitingWeb();
        }
        return ha;
    }

    public boolean inInterval(){
        try {
            long curr = System.currentTimeMillis();
            for (Point2D<String> i : intervals) {
                long min = DateUtils.composeTimeOfToday(i.getX()).getTime();
                long max = DateUtils.composeTimeOfToday(i.getY()).getTime();
                if (min <= curr && curr <= max)
                    return true;
            }
        } catch (ParseException e) {
            System.out.println(this.toString()+"模拟人工，时间段转换异常");
            e.printStackTrace();
        }
        return false;
    }

}
